<template>
  <div class="order-management p-6 bg-gray-50 min-h-screen">
    <!-- 搜索过滤栏 - 响应式优化 -->
    <el-card class="!border-none mb-4 shadow-sm">
      <div class="search-filter">
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" :lg="4" :xl="3">
            <el-input
              placeholder="销售订单号"
              v-model="searchParams.salesOrderNo"
              clearable
              size="small"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4" :xl="3">
            <el-input
              placeholder="单据编码"
              v-model="searchParams.documentCode"
              clearable
              size="small"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4" :xl="3">
            <el-input
              placeholder="物料编码"
              v-model="searchParams.materialCode"
              clearable
              size="small"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="4" :xl="3">
            <el-input
              placeholder="物料名称"
              v-model="searchParams.materialName"
              clearable
              size="small"
            />
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4">
            <el-date-picker
              v-model="searchParams.dateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              class="w-full"
            />
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4">
            <el-button
              type="primary"
              @click="handleSearch"
              size="small"
              class="w-full"
              >搜索</el-button
            >
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 操作按钮栏 - 增加图标和动画 -->
    <el-card class="!border-none mb-4 shadow-sm">
      <div class="action-buttons flex flex-wrap gap-3">
        <el-button type="primary" class="!px-5">单据</el-button>
        <el-button type="success" @click="get">新增</el-button>
        <el-button type="warning" @click="handleExport">导出</el-button>
        <el-button
          type="danger"
          @click="handleDelete('批量删除')"
          :disabled="selectedRows.length === 0"
          >批量删除</el-button
        >
        <el-divider direction="vertical" />
      </div>
    </el-card>

    <!-- 数据表格 - 优化数据展示 -->
    <el-card class="!border-none shadow-sm">
      <el-table
        :data="tableData"
        stripe
        highlight-current-row
        style="width: 100%"
        header-row-class-name="custom-header"
        class="rounded-lg overflow-hidden"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialsBliiId" label="序号" width="50" />
        <el-table-column prop="salesPerson" label="销售员" min-width="80" />
        <el-table-column
          prop="salesOrderNo"
          label="销售订单号"
          min-width="150"
        />
        <el-table-column
          prop="orderDeliveryDate"
          label="订单交期"
          min-width="120"
        >
          <template #default="scope">
            {{ dayjs(scope.row.orderDeliveryDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column prop="billCode" label="单据编码" min-width="120" />
        <el-table-column prop="materialName" label="物料名称" min-width="150" />
        <el-table-column prop="materialCode" label="物料编码" min-width="120" />
        <el-table-column prop="demandquantity" label="数量" min-width="80">
        </el-table-column>
        <el-table-column prop="mainUnit" label="主计量" min-width="80" />
        <el-table-column label="物料清单" prop="businessType" min-width="120">
        </el-table-column>
        <el-table-column label="单据状态" prop="billStatus" min-width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.billStatus)">{{
              scope.row.billStatus
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="billDate" label="单据日期" min-width="120">
          <template #default="scope">
            {{ dayjs(scope.row.billDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="upd(scope.row.materialCode)"
              >查看</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="
                handleDelete(scope.row.materialsBliiId, [
                  scope.row.materialCode,
                ])
              "
              style="margin-left: 5px"
              >删除</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="upd(scope.row.materialCode)"
              style="margin-left: 5px"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="form1.PageIndex"
          v-model:page-size="form1.PageSize"
          :page-sizes="[1, 3, 15, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="form1.TotalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
//分页
const handleSizeChange = (newSize: number) => {
  form1.PageSize = newSize;
  searchProducts();
};
//分页
const handleCurrentChange = (newPage: number) => {
  form1.PageIndex = newPage; // 正确更新页码
  searchProducts();
};
//显示
const searchProducts = () => {
  axios
    .get("http://localhost:5202/api/Log/GetMaterialsBliiProcurement", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex, // 确保参数名与后端一致
      },
    })
    .then((res) => {
      tableData.value = res.data.data.list;
      // 注意：后端返回的总记录数是 Data.PageCount，但需要根据总记录数计算总页数
      form1.TotalCount = res.data.data.pageCount; // 总记录数
      form1.PageCount = Math.ceil(form1.TotalCount / form1.PageSize); // 前端计算总页数
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};
const get = () => {
  router.push("/AddProduce");
};
// 模拟数据
const tableData = ref([]);

const searchParams = reactive({
  salesOrderNo: "",
  documentCode: "",
  materialCode: "",
  materialName: "",
  dateRange: [],
});

const handleSearch = () => {
  // 实际开发中调用接口传递 searchParams 进行搜索
  console.log("搜索参数", searchParams);
};
//跳转修改
const upd = (materialCode: string) => {
  router.push({
    path: "/UpdateProduce",
    query: {
      materialCode: materialCode,
    },
  });
};
const handleExport = () => {
  // 调用导出接口
  console.log("导出数据");
};
// 选中的行
// 修改选择处理逻辑（确保ID有效性）
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};
// 优化后的删除方法
const handleDelete = async (id: any, materialCode: any = []) => {
  try {
    let ids = [];
    let materialCodes = [];

    if (id === "批量删除") {
      // 批量删除逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning("请至少选择一条记录");
        return;
      }
      ids = selectedRows.value.map((item) => item.materialsBliiId);
      materialCodes = selectedRows.value.map((item) => item.materialCode);

      await ElMessageBox.confirm(
        `确定要删除${selectedRows.value.length}条记录？`,
        "警告",
        { type: "warning" }
      );
    } else {
      // 单条删除逻辑
      ids = [id];
      materialCodes = materialCode;

      await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
        type: "warning",
      });
    }

    // 统一请求处理
    const params = new URLSearchParams();
    params.append("Table", "MaterialsBlii");
    params.append("TableId", "MaterialsBliiId");
    ids.forEach((id) => params.append("Ids", id.toString()));
    materialCodes.forEach((num) => params.append("MaterialCode", num));

    const res = await axios.delete(
      "http://localhost:5027/api/Log/DeleteMultiTableData",
      {
        params: params,
        paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
      }
    );

    if (res.data.code === 500) {
      ElMessage.success(res.data.message);
      searchProducts();
      if (id === "批量删除") {
        selectedRows.value = []; // 清空选择
      }
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略用户取消操作
      ElMessage.error(`操作失败: ${error.message}`);
    }
  }
};
// 单据状态类型映射
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    开立: "info",
    审核: "success",
    驳回: "danger",
  };
  return statusMap[status] || "info";
};

onMounted(() => {
  searchProducts();
});
</script>

<style scoped lang="scss">
.order-management {
  :deep(.el-card) {
    transition: box-shadow 0.3s ease;
    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .search-filter {
    .el-col {
      margin-bottom: 12px;
    }
  }

  .category-btn {
    transition: all 0.3s ease;
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }

  :deep(.custom-header) {
    th {
      @apply bg-blue-50 font-medium text-gray-600;
    }
  }

  :deep(.el-table__row) {
    transition: all 0.3s ease;
    &:hover {
      transform: translateX(4px);
      box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
    }
  }

  .el-tag {
    &.el-tag--light {
      &.el-tag--success {
        background-color: #f0f9eb;
        border-color: #e1f3d8;
      }
      &.el-tag--info {
        background-color: #e6f7ff;
        border-color: #d9ecff;
      }
    }
  }
}
.order-management {
  :deep(.el-card) {
    transition: box-shadow 0.3s ease;
    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .search-filter {
    .el-col {
      margin-bottom: 12px;
    }
  }

  .action-buttons {
    .el-button {
      text-align: center;
      padding: 5px 15px; /* 调整内边距让文字更居中 */
    }
  }

  :deep(.custom-header) {
    th {
      @apply bg-blue-50 font-medium text-gray-600;
    }
  }

  :deep(.el-table__row) {
    transition: all 0.3s ease;
    &:hover {
      transform: translateX(4px);
      box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
    }
  }

  .el-tag {
    &.el-tag--light {
      &.el-tag--success {
        background-color: #f0f9eb;
        border-color: #e1f3d8;
      }
      &.el-tag--info {
        background-color: #e6f7ff;
        border-color: #d9ecff;
      }
    }
  }
}
</style>